require 'fileutils'

default_platform(:ios)

platform :ios do
 
  before_all do
    # fastlane spaceauth -u fengsh998@163.com
    # fastlane fastlane-credentials remove --username fengsh998@163.com
    ENV["FASTLANE_ITC_TEAM_ID"] = '1112582'
    ENV["FASTLANE_USER"] = "fengsh998@163.com"
    ENV["FASTLANE_APPLE_APPLICATION_SPECIFIC_PASSWORD"] = 'dazu-afcc-jpgx-txoj'
    ENV["DELIVER_ITMSTRANSPORTER_ADDITIONAL_UPLOAD_PARAMETERS"] = "-t Aspera"
  end

desc '私有pod 一键脚本'
lane :release do |options|

tagNum = options[:version]
podspecName = podspec_name

# 航道上需要执行的操作
# 具体action到 https://docs.fastlane.tools/actions 上面查找
# 这里的路径以仓库根目录为准

# 1、修改spec文件（修改s.version，s.description等）
# 2、pod install （使Example与pod下来的库产生关联）
cocoapods(
  clean: true,
  podfile: "./Example/Podfile"
)

system 'pod repo update AppRepo'

# 一次性问答密码
# system 'ssh-add ~/.ssh/id_rsa'
# 修改版本号
change_version(podspecName, tagNum)

# 3、提交本地仓库代码至远程仓库
git_add(path: ".")
git_commit(path: ".", message: "upgrade repo",allow_nothing_to_commit: true)

push_to_git_remote()

# 4、打标签，并提交至远程
# 先验证tag是否存在，如果存在则删除本地标签和远程标签
if git_tag_exists(tag: tagNum)
  UI.message("您输入的tag:#{tagNum}已存在，即将自动清除") 
  remove_git_tag(tagNum: tagNum)
end
add_git_tag(
  tag: tagNum
)

push_git_tags


# git clone https://github.com/CocoaPods/Specs.git ~/.cocoapods/repos/trunk
if File.directory?("~/.cocoapods/repos/AppRepo") == false
  system 'git clone https://gitee.com/i-os-app-template-with-ctmediator/specs.git ~/.cocoapods/repos/AppRepo'
end

# 5、验证spec，并提至私有索引库
# pod_lib_lint(allow_warnings: true, no_subspecs: true, quick: true, no_clean: true,skip_tests: true, sources: ["https://gitlab.btpoc.com/app/ios/componentrepo.git"])
# , "https://github.com/CocoaPods/Specs"
# 因为本地索引库repo的名字是基本上不会去改变的，所以这里直接写死 AppRepo
# podspec的名字需要由外界传入
pod_push(path: "#{podspecName}.podspec",
 repo: "AppRepo",
 allow_warnings: true,
 sources: ["https://gitee.com/vencents-app-template/specs.git"]
)

end


lane :CreatePod do |options|

  podName = options[:podName]
  podUrl = options[:podUrl]

  create_private_pod(podName: podName, podUrl: podUrl)

end

lane :add do |options|

  Dir.chdir('../') do

    podUrl = options[:remoteUrl]

    system "git remote add origin #{podUrl}"

    system 'git checkout -b develop'
  end
end

lane :GetFlutterSDK do |options|
  tagNum = options[:version]
  frameworkMode = "Debug"
  if options[:mode] == "Release"
    frameworkMode = options[:mode]
  end
  podspecName = podspec_name
  sdksDir = "../#{podspecName}/SDKS"

  Dir.chdir('../../') do
    system "flutter build ios-framework"
  end

  if Dir.exists?(sdksDir) == false 
    FileUtils.mkdir(sdksDir)
  end

  FileUtils.rm_rf(Dir.glob("#{sdksDir}/*"))
  
  path = "../../build/ios/framework/#{frameworkMode}"
  Dir.entries(path).each do |sub|         
    if sub != '.' && sub != '..' && sub != '.DS_Store'   
      if File.directory?("#{path}/#{sub}") 
        FileUtils.cp_r "#{path}/#{sub}", sdksDir, :verbose => true
      end
    end
  end

end

lane :FlutterSDKBuild do |options|
  flutterdir = options[:dir]
  # system "export PUB_HOSTED_URL=https://pub.flutter-io.cn"
  # system "export FLUTTER_STORAGE_BASE_URL=https://storage.flutter-io.cn"
  Dir.chdir("../../#{flutterdir}") do
    system "flutter drive"
  end

  Dir.chdir("../Example") do
    system "pod update"
  end
end

lane :GetFlutterSDKJenkins do |options|
  frameworkMode = "Debug"
  if options[:mode] == "Release"
    frameworkMode = options[:mode]
  end
  podspecName = podspec_name
  sdksDir = "../#{podspecName}/SDKS"
  flutterdir = options[:dir]

  Dir.chdir("../../#{flutterdir}") do
    system "flutter build ios-framework"
  end

  if Dir.exists?(sdksDir) == false 
    FileUtils.mkdir(sdksDir)
  end

  FileUtils.rm_rf(Dir.glob("#{sdksDir}/*"))
  
  path = "../../#{flutterdir}/build/ios/framework/#{frameworkMode}"
  Dir.entries(path).each do |sub|         
    if sub != '.' && sub != '..' && sub != '.DS_Store'  
      if File.directory?("#{path}/#{sub}") 
        FileUtils.cp_r "#{path}/#{sub}", sdksDir, :verbose => true
      end
    end
  end
end

  
def podspec_name 
  podspecName = File.basename(File.expand_path("..", Dir.pwd), Dir.getwd)
  Dir.children("..").each{|x| 
    fileName = x.sub!(/\..*/,"")
    if podspecName.casecmp? fileName
      podspecName = fileName
    end
  }
  podspecName
end


def change_version(podspecName, version)
  path = "../#{podspecName}.podspec"
  
  return unless File.exists? path

  lines = IO.readlines(path).map do |line|
    if line.include? "s.version          ="
      print "版本号修改为:#{version}\n"
      line = "  s.version          = '#{version}'"
    else
      line
    end
    end
      File.open(path, 'w') do |file|
      print "写入文件\n"
      file.puts lines 
  end
print "版本号写入完成\n"
end


def setFastlaneSession
  spaceauth_output = `fastlane spaceauth -u best_sxz@163.com`
  # regex the output for the value we need
  fastlane_session_regex = %r{Pass the following via the FASTLANE_SESSION environment variable:\n(?<session>.+)\n\n\nExample:\n.+}
  new_session = nil
  if match = spaceauth_output.match(fastlane_session_regex)
    # Strip out the fancy formatting
    new_session = match[:session].gsub("\e[4m\e[36m", "").gsub("\e[0m\e[0m", "")
  end

  if new_session.nil?
    puts "Unable to obtain new session via fastlane spaceauth"
    exit 1
  else
    ENV["FASTLANE_SESSION"] = new_session
  end

end

#获取项目名称
def getProjectName
    path = "../"
    Dir.entries(path).each do |sub|         
      if sub != '.' && sub != '..' && sub != '.DS_Store'  
        extname = (File.extname  sub)
        if extname == '.xcodeproj'
          return podspecName = (File.basename sub, extname)
        end 
      end
    end
end

#生成构建文件名
def makeIpaName(version) 
  packageVersion = (Date.today - 1).strftime("%Y%m%d")
  currentTime = Time.new.hour
  if currentTime >= 9  
    packageVersion = (Date.today).strftime("%Y%m%d")    
  end

  timeString = Time.new.strftime("%Y%m%d%H%M%S%L")
  shortPath = version + '.' + packageVersion + '.' + timeString
  return shortPath
end


desc "构建APPStore包或TestFlight包"
lane :BuildForAppStore do | args |
  ipa_name = args[:ipaName]
  case ipa_name
  when "havalAppStore"
    ENV["FASTLANE_APP_IDENTIFIER"] = "com.gwm.connect"
  when "weyAppStore"
    ENV["FASTLANE_APP_IDENTIFIER"] = "com.gwm.wey"
  when "oraAppStore"
    ENV["FASTLANE_APP_IDENTIFIER"] = "com.gwm.superora"
  when "pickupAppStore"
    ENV["FASTLANE_APP_IDENTIFIER"] = "com.gwm.truck"
  else
    UI.user_error!("未找到支持的ipa名,请联系IOS-Jenkins管理员！")
  end

  #构建APPStore,ADHoc
  BuildArchiveProject( 99,
                      ipa_name,
                      args[:versionNum],
                      args[:buildNum],
                      args[:envDefault],
                      args[:uploadPlatform],
                      "","","","","","",""
       )
end

desc "构建企业包"
lane :BuildForEnterprise do | args |
  ipa_name = args[:ipaName]
  # 构建企业包，上传浦公英和firim       

  BuildArchiveProject(299,
                      ipa_name,
                      args[:versionNum],
                      args[:buildNum],
                      args[:envDefault],
                      "", # uploadplatform
                      args[:pgyFlag],
                      args[:pgyApiKey],
                      args[:pgyUserKey],
                      args[:ipaPassword],
                      args[:firFlag],
                      args[:firApiToken],
                      args[:pgyDesc]
           )
end

def todo_pod_update
  # puts(Dir.pwd)
  cmds = []
  cmds << "cd '../' &&"
  cmds << "pod update"
  
  # system "cd '../' && pod update"
  Actions.sh(cmds) do |status, result, command|
    unless status.success?
      say("Pod update 更新异常！")
      UI.user_error!("Pod update 更新异常！")
    end
  end
end

def to_update_project_plist(env,version,buildNo)
  projectName = getProjectName
  set_info_plist_value(path: "./#{projectName}/Info.plist",
                        key: "APPCustomerKey",
                        subkey: "ENV_DEFAULT",
                        value: "#{env}"
                      )
  increment_version_number(
    version_number: version
  )
  increment_build_number(
    build_number: buildNo
  )
  update_info_plist
end

def BuildArchiveProject(certType,ipa_name,version_num,buildNum,envDefault,uploadPlatform,
  pgyFlag,pgyApiKey,pgyUserKey,ipaPassword,firFlag,firApiToken,pgyDesc)

  # 构建前，更新pod 
  say("准备更新Pod,请耐心等待!")
  todo_pod_update

  # 打包版本号
  shortPath = makeIpaName(version_num)
  version = shortPath + '.' + last_git_commit[:abbreviated_commit_hash]
  #输出路径
  output_path = "../iOSIPAPath/#{ipa_name}/#{ipa_name}#{shortPath}"


  UI.header(make_font_characters(typeName: "xc"))

  ctype = certType 

  case ctype
  when 99
    
    to_update_project_plist(envDefault, version_num, buildNum)

    export_method = 'app-store'

    if uploadPlatform == "Release_AdHoc"
      UI.header(make_font_characters(typeName: "tf"))
    else 
      UI.header(make_font_characters(typeName: "appstore"))
    end

    logs = "\n\n\n"
    logs += "                                 开始构建：#{ipa_name}\n"
    logs += "～～～～～～～～～～～～～～～～～～～构建参数-start-～～～～～～～～～～～～～～～～～～～～～～～～\n"
    logs += "                                 内部版本号：#{version}\n"
    logs += "                                 发布平台：#{uploadPlatform}\n"
    logs += "                                 版本号：#{version_num}\n"
    logs += "                                 构建号：#{buildNum}\n"
    logs += "                                 应用程序运行环境：#{envDefault}\n"
    logs += "                                 ipa包储存路径：#{output_path}\n"
    logs += "～～～～～～～～～～～～～～～～～～～构建参数-end-``～～～～～～～～～～～～～～～～～～～～～～～～\n"
    logs += "\n\n\n"
    UI.header(logs)
    # 设置session
    setFastlaneSession
    say("开始打包啦!")
    begin
      gym(
        #输出的ipa名称
        output_name:"#{ipa_name}#{version}",
        # 是否清空以前的编译信息 true：是
        clean:true,
        # 指定打包方式，Release 或者 Debug
        configuration:uploadPlatform,
        # 指定打包所使用的输出方式，目前支持app-store, package, ad-hoc, enterprise, development
        export_method:export_method,
        # 指定输出文件夹
        output_directory:"#{output_path}",
        silent: "true"
      )
    rescue
      say("成功失败!")
      UI.user_error!(make_font_characters(typeName: "fail")) ##{$?.exitstatus}
    end

    sleep 1
    UI.header("上传TestFlight！")
    say("成功打包，上传 TestFlight！")
    begin
      upload_to_testflight(skip_waiting_for_build_processing:true)
    rescue
      UI.user_error!(make_font_characters(typeName: "fail")) ##{$?.exitstatus}
    end

  when 299
    to_update_project_plist(envDefault, version,buildNum)

    UI.header(make_font_characters(typeName: "enp"))
    
    logs = "\n\n\n"
    logs += "                                 开始构建：#{ipa_name}\n"
    logs += "～～～～～～～～～～～～～～～～～～～构建参数-start-～～～～～～～～～～～～～～～～～～～～～～～～\n"
    logs += "                                 内部版本号：#{version}\n"
    logs += "                                 版本号：#{version_num}\n"
    logs += "                                 构建号：#{buildNum}\n"
    logs += "                                 应用程序运行环境：#{envDefault}\n"
    logs += "                                 ipa包储存路径：#{output_path}\n"
    logs += "～～～～～～～～～～～～～～～～～～～构建参数-end-``～～～～～～～～～～～～～～～～～～～～～～～～\n"
    logs += "\n\n\n"
    UI.header(logs)

    say("开始打包啦!")

    begin
      gym(
          #输出的ipa名称
          output_name:"#{ipa_name}#{version}",
          # 是否清空以前的编译信息 true：是
          clean:true,
          # 指定打包方式，Release 或者 Debug
          configuration:'Release_Enterprise',
          # 指定打包所使用的输出方式，目前支持app-store, package, ad-hoc, enterprise, development
          export_method:'enterprise',
          # 指定输出文件夹
          output_directory:"#{output_path}",
          silent: "true"
          # toolchain:"com.360jiagubao.1.5.0"
      )

    rescue
      say("成功失败!")
      UI.user_error!(make_font_characters(typeName: "fail")) ##{$?.exitstatus}
    end
    
    say("打包成功!")

    sleep 1
    begin
      if !firApiToken.empty? && firFlag == true
        UI.header("开始上传fir")
        say("成功打包，上传firim！")
        firim(firim_api_token: firApiToken, app_passwd: ipaPassword)
      end

      if !pgyApiKey.empty? && pgyFlag == true
        UI.header("开始上传蒲公英")
        say("成功打包，开始上传蒲公英!")
        pgyer(api_key: pgyApiKey, user_key: pgyUserKey, password: ipaPassword, update_description: pgyDesc)
      end
    rescue
      UI.user_error!(make_font_characters(typeName: "fail")) ##{$?.exitstatus}
    end
  else 
    UI.user_error!("别看了!赶紧查下参数是否传错了！")
  end

  UI.header(make_font_characters(typeName: "jobs"))

  UI.header(make_font_characters(typeName: "suc"))

end


end